const gameBoard = document.getElementById('game-board');
const restartButton = document.getElementById('restart-button');
const boardSize = 20;
let snake = [{ x: 10, y: 10 }];
let food = { x: 15, y: 15 };
let direction = { x: 0, y: 0 };
let score = 0;

function createBoard() {
    for (let i = 0; i < boardSize * boardSize; i++) {
        const cell = document.createElement('div');
        cell.classList.add('cell');
        gameBoard.appendChild(cell);
    }
}

function drawSnake() {
    snake.forEach(segment => {
        const cell = document.querySelector(`.cell:nth-child(${segment.y * boardSize + segment.x + 1})`);
        cell.classList.add('snake');
    });
}

function drawFood() {
    const cell = document.querySelector(`.cell:nth-child(${food.y * boardSize + food.x + 1})`);
    cell.classList.add('food');
}

function updateGame() {
    gameBoard.querySelectorAll('.cell').forEach(cell => cell.classList.remove('snake', 'food'));
    drawSnake();
    drawFood();
}

function moveSnake() {
    const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
    snake.unshift(head);

    if (head.x === food.x && head.y === food.y) {
        score++;
        food = {
            x: Math.floor(Math.random() * boardSize),
            y: Math.floor(Math.random() * boardSize)
        };
    } else {
        snake.pop();
    }

    if (head.x < 0 || head.x >= boardSize || head.y < 0 || head.y >= boardSize || snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)) {
        alert(`游戏结束，你的得分是：${score}`);
        restartButton.style.display = 'block';
        clearInterval(gameInterval);
    }
}

function changeDirection(event) {
    switch (event.key) {
        case 'ArrowUp':
            if (direction.y === 0) direction = { x: 0, y: -1 };
            break;
        case 'ArrowDown':
            if (direction.y === 0) direction = { x: 0, y: 1 };
            break;
        case 'ArrowLeft':
            if (direction.x === 0) direction = { x: -1, y: 0 };
            break;
        case 'ArrowRight':
            if (direction.x === 0) direction = { x: 1, y: 0 };
            break;
    }
}

function restartGame() {
    snake = [{ x: 10, y: 10 }];
    food = { x: 15, y: 15 };
    direction = { x: 0, y: 0 };
    score = 0;
    restartButton.style.display = 'none';
    updateGame();
    gameInterval = setInterval(gameLoop, 200);
}

document.addEventListener('keydown', changeDirection);
restartButton.addEventListener('click', restartGame);

function gameLoop() {
    moveSnake();
    updateGame();
}

createBoard();
updateGame();
let gameInterval = setInterval(gameLoop, 200);